#!/usr/bin/env python3
"""Final video composition script - handles Chinese paths correctly"""

import os, subprocess, re, sys

BASE = r'E:\集群文件夹\factory_os\short_video_real_data_pipeline\phase4b_90s_formal_sample\v22_kimi_claude_loop\full_story_douyin_video'
FFMPEG = r'D:\AI_WORKSPACE\tools\ffmpeg\ffmpeg.exe'
CLIPS = os.path.join(BASE, '05_clips')
VO = os.path.join(BASE, '02_voiceover')
VIDEO_OUT = os.path.join(BASE, '06_video', 'claude_code_self_evolving_video_workflow_douyin_v1.mp4')

SCENE_ORDER = ['title','punch','recording_fail','five_fails','ai_drift','chatgpt_fix',
               'python_render','multi_agent','log_lines','kimi_intro','score_bars',
               'v9_peak','v10_crash','v11_recovery','lesson','rollback',
               'review_portal','http_verify','summary','final_montage','end_card']

def run_ffmpeg(cmd, desc):
    print(f"\n{'='*60}")
    print(f"  {desc}")
    print(f"{'='*60}")
    result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace')
    if result.returncode != 0:
        print(f"  ⚠ Return code: {result.returncode}")
        err = result.stderr[-800:] if len(result.stderr) > 800 else result.stderr
        print(f"  STDERR: {err}")
    else:
        print(f"  ✅ OK (rc=0)")
    return result

def get_duration(filepath):
    result = subprocess.run([FFMPEG, '-i', filepath], capture_output=True, text=True, encoding='utf-8', errors='replace')
    m = re.search(r'Duration: (\d+):(\d+):(\d+\.\d+)', result.stderr)
    if m:
        h, mi, s = int(m.group(1)), int(m.group(2)), float(m.group(3))
        total_s = h*3600 + mi*60 + s
        print(f"  Duration: {h}h{mi}m{s}s ({total_s:.1f}s)")
        return total_s
    return 0

# Step 1: Create concat file with proper path format
concat_file = os.path.join(CLIPS, 'concat_unix.txt')
with open(concat_file, 'w', encoding='utf-8') as f:
    for s in SCENE_ORDER:
        mp4_path = os.path.join(CLIPS, s + '.mp4')
        # Use forward slashes
        mp4_path = mp4_path.replace(os.sep, '/')
        f.write(f"file '{mp4_path}'\n")

print(f"Concat file created with {len(SCENE_ORDER)} scenes")
for line in open(concat_file, encoding='utf-8').readlines()[:3]:
    print(f"  {line.rstrip()[:80]}...")

# Verify all files exist
missing = []
for s in SCENE_ORDER:
    p = os.path.join(CLIPS, s + '.mp4')
    if not os.path.exists(p):
        missing.append(s)
if missing:
    print(f"\n⚠ Missing scene clips: {missing}")
    sys.exit(1)
print("\nAll scene clips verified ✓")

# Step 2: Concatenate scenes
joined_path = os.path.join(CLIPS, 'scenes_joined.mp4')
run_ffmpeg([
    FFMPEG, '-y', '-f', 'concat', '-safe', '0',
    '-i', concat_file,
    '-c', 'copy',
    joined_path
], "Step 1: Concatenating 21 scene clips")

if os.path.exists(joined_path):
    print(f"  Output: {joined_path} ({os.path.getsize(joined_path)/1024/1024:.1f} MB)")
    get_duration(joined_path)

    # Step 3: Add audio
    audio = os.path.join(VO, 'voiceover_master_fast.wav')
    if not os.path.exists(audio):
        # Try alternative paths
        audio = os.path.join(VO, 'voiceover_master.wav')

    print(f"\n  Audio source: {audio}")

    run_ffmpeg([
        FFMPEG, '-y',
        '-i', joined_path,
        '-i', audio,
        '-c:v', 'libx264', '-preset', 'medium', '-crf', '20',
        '-c:a', 'aac', '-b:a', '192k',
        '-pix_fmt', 'yuv420p',
        '-movflags', '+faststart',
        '-shortest',
        VIDEO_OUT
    ], "Step 2: Adding voiceover audio")

    if os.path.exists(VIDEO_OUT):
        size_mb = os.path.getsize(VIDEO_OUT) / (1024*1024)
        print(f"\n{'='*60}")
        print(f"✅ VIDEO COMPOSITION COMPLETE")
        print(f"{'='*60}")
        print(f"  Output: {VIDEO_OUT}")
        print(f"  Size: {size_mb:.1f} MB")
        get_duration(VIDEO_OUT)
    else:
        print(f"\n❌ Final video not created!")

print("\nDone.")
